﻿using System.Drawing;

namespace LeRenard.Libraries.Drawing.GdiPlus.Forms
{
    /// <summary>
    /// Backbuffer to draw frames on.    
    /// </summary>
    public sealed class Target : ITarget
    {
        #region Members
        /// <summary>
        /// Gets the <see cref="Graphics"/> GDI surface to draw on.
        /// </summary>
        public Graphics Graphics
        {
            get
            {
                return _graphics;
            }
        }
        private Graphics _graphics;
        #endregion

        #region Construction, Deconstruction
        /// <summary>
        /// Creates a new <see cref="Target"/> object based on a given <see cref="Graphics"/>.
        /// </summary>        
        public Target(Graphics graphics)
        {
            _graphics = graphics;
        }

        /// <summary>
        /// Initializes the <see cref="Target"/> object.
        /// </summary>        
        private void Initialize()
        {
            Deinitialize();
        }
        /// <summary>
        /// Initializes the <see cref="Target"/> object.
        /// </summary>
        /// <param name="graphics">The new <see cref="Graphics"/> target.</param>
        private void Initialize(Graphics graphics)
        {
            Deinitialize();

            _graphics = graphics;
        }

        /// <summary>
        /// Deinitializes the <see cref="Target"/> object.
        /// </summary>
        private void Deinitialize()
        {
            if (_graphics != null) {
                _graphics.Dispose();
                _graphics = null;
            }
        }

        /// <summary>
        /// Releases all resources used by this <see cref="Target"/>.
        /// </summary>
        public void Dispose()
        {
            Deinitialize();
        }

        /// <summary>
        /// Reallocates the target.
        /// </summary>
        /// <param name="graphics">The new <see cref="Graphics"/> target.</param>
        public void ReAllocate(Graphics graphics)
        {
            Deinitialize();
            Initialize(graphics);
        }
        #endregion
    }
}
